//
// Created by 吴喆 on 2020/3/26.
//

#include "StateMachine.h"
#include "Playable.h"


void StateMachine::update(Playable &playable) {
    if (summerFirst) {
        currentState->enter(playable);
        summerFirst = false;
    }

    auto *state = currentState->update(playable);
    if (state != nullptr) {
        delete currentState;
        currentState = state;
        // 在新的状态上调用 enter 行为。
        currentState->enter(playable);
    }
}

void StateMachine::handleInput(Playable &playable, KeyEvent *pEvent) {
    auto state = currentState->handleInput(playable, pEvent);
    if (state != nullptr) {
        delete currentState;
        currentState = state;
        currentState->enter(playable);
    }
}

StateMachine::~StateMachine() {
    delete currentState;
}


PlayableState *PlayableState::update(Playable &playable) {
    for (auto animationEntry : animationMap) {
        if (animationEntry.second != playable.currentAnimation) {
            // only update
            animationEntry.second->update();
        }
    }
    return nullptr;
}

void PlayableState::enter(Playable &playable) {
    initAnimation();
    // if there is no animation, skip
    if (animationMap.empty()) {
        return;
    }
    // default first
    playable.currentAnimation = animationMap[0];
}

PlayableState *PlayableState::handleInput(Playable &, KeyEvent *) {
    return nullptr;
}
